﻿Shader "Custom/TestShader6"
{
	Properties
	{
		_MainTex("MainTex", 2D) = "white" {}
		_BumpMap("Normal Map", 2D) = "bump" {}
		_BumpScale("Bump Scale", float) = 1.0
		_Color("Color", color) = (1,1,1,1)
		_Diffuse("Diffuse", color) = (1,1,1,1)
		_Specular("Specular", color) = (1,1,1,1)
		_Gloss("Gloss", Range(8, 128)) = 20
	}
	SubShader
	{
		Pass
		{
			Tags{ "LightMode" = "ForwardBase" }

			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag
			#include "Lighting.cginc"	

			sampler2D _MainTex;
			float4 _MainTex_ST;
			sampler2D _BumpMap;
			float4 _BumpMap_ST;
			float _BumpScale;
			fixed4 _Color;
			fixed4 _Diffuse;
			fixed4 _Specular;
			float _Gloss;

			struct a2v
			{
				float4 vertex : POSITION;
				float3 normal : NORMAL;
				float4 texcoord : TEXCOORD0;
				float4 tangent : TANGENT;
			};

			struct v2f
			{
				float4 pos : SV_POSITION;
				float4 uv :TEXCOORD0;
				float4 T2W1:TEXCOORD1;
				float4 T2W2:TEXCOORD2;
				float4 T2W3:TEXCOORD3;
			};

			v2f vert(a2v v)
			{
				v2f o;
				o.pos = UnityObjectToClipPos(v.vertex);
				o.uv.xy = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw;
				o.uv.zw = v.texcoord.xy * _BumpMap_ST.xy + _BumpMap_ST.zw;

				float3 worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
				float3 worldTangent = UnityObjectToWorldDir(v.tangent.xyz);
				float3 worldNormal = UnityObjectToWorldNormal(v.normal);
				float3 worldBinormal = cross(worldNormal, worldTangent) * v.tangent.w;
				o.T2W1 = float4(worldTangent.x, worldBinormal.x, worldNormal.x, worldPos.x);
				o.T2W2 = float4(worldTangent.y, worldBinormal.y, worldNormal.y, worldPos.y);
				o.T2W3 = float4(worldTangent.z, worldBinormal.z, worldNormal.z, worldPos.z);
				return o;
			}

			fixed4 frag(v2f i) : SV_Target
			{
				fixed3 worldPos = float3(i.T2W1.w, i.T2W2.w, i.T2W3.w);

				fixed4 packedNormal = tex2D(_BumpMap, i.uv.zw);
				fixed3 tangentNormal = UnpackNormal(packedNormal);
				tangentNormal.xy *= _BumpScale;
				tangentNormal.z = sqrt(1.0 - saturate(dot(tangentNormal.xy, tangentNormal.xy)));

				fixed3 worldNormal = normalize(fixed3(dot(i.T2W1.xyz, tangentNormal), dot(i.T2W2.xyz, tangentNormal), dot(i.T2W3.xyz, tangentNormal)));

				fixed3 albedo = tex2D(_MainTex, i.uv.xy).rgb * _Color.rgb;
				fixed3 ambient = albedo * UNITY_LIGHTMODEL_AMBIENT.xyz;
				fixed3 worldLight = normalize(UnityWorldSpaceLightDir(worldPos));

				fixed3 diffuse = albedo * _Diffuse.rgb * _LightColor0.rgb * saturate(dot(worldNormal, worldLight));

				fixed3 viewDir = normalize(UnityWorldSpaceViewDir(worldPos));

				fixed3 halfDir = normalize(viewDir + worldLight);

				fixed3 specular = _Specular.rgb * _LightColor0.rgb * pow(max(0,dot(worldNormal, halfDir)), _Gloss);

				return fixed4(diffuse + ambient + specular, 1);
			}

			ENDCG
		}
	}
}
